package org.neptune.service.config;

import java.io.Serializable;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.neptune.common.constant.NeptuneConstant;
import org.neptune.service.redis.RedisRepository;
import org.neptune.service.redis.RedissonUtil;

public class MyRedisSessionDao extends EnterpriseCacheSessionDAO {

	private RedisRepository redisRepository;

	private int expireTime;

	public MyRedisSessionDao(RedisRepository redisRepository) {
		this.redisRepository = redisRepository;
	}

	public MyRedisSessionDao(RedisRepository redisRepository, int expireTime) {
		this.redisRepository = redisRepository;
		this.expireTime = expireTime;
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = super.doCreate(session);
		String key = RedissonUtil.getRedisKey(NeptuneConstant.REDIS_SHIRO_SESSION_CACHE,
				session.getId().toString());
		redisRepository.set(key, session, expireTime);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		String key = RedissonUtil.getRedisKey(NeptuneConstant.REDIS_SHIRO_SESSION_CACHE,
				sessionId.toString());
		return redisRepository.get(key, Session.class);
	}

	// 设置session的最后一次访问时间
	@Override
	protected void doUpdate(Session session) {
		super.doUpdate(session);
		String key = RedissonUtil.getRedisKey(NeptuneConstant.REDIS_SHIRO_SESSION_CACHE,
				session.getId().toString());
		redisRepository.expire(key, expireTime);
	}

	// 删除session
	@Override
	protected void doDelete(Session session) {
		super.doDelete(session);
		String key = RedissonUtil.getRedisKey(NeptuneConstant.REDIS_SHIRO_SESSION_CACHE,
				session.getId().toString());
		redisRepository.remove(key);
	}
}
